<template>
  <div class="msgBox"  ref="msgBody" >
    <div v-for="(item, index) in messages" :key="index" :class="item.userStyle">{{ item.message }}</div>
  </div>
</template>


<script>
import { ref, onMounted, watch , nextTick } from 'vue';

export default {
  name: 'MessageComponent',
  setup() {
    const messages = ref([]);
    const msgBody = ref(null);

    const addMessage = (text) => {
      messages.value.push(text);
    };

    const messageUpdate = (text) => {
      let chatMsg =  messages.value[messages.value.length - 1];
      if(chatMsg.userStyle != "gpt") return;
      chatMsg.message =  text;
    }

    onMounted(() => {
      // Simulate adding a message
      // setInterval(()=>{
      //   addMessage({
      //     "message":"fsdfsafdsafsa",
      //     "userStyle":"gpt"
      //   })
      // },1000)
    });

    watch(() => messages.value, (newVal, oldVal) => {
      // Your code here
      nextTick(() => {
        if (msgBody.value) {
          msgBody.value.scrollTop = msgBody.value.scrollHeight;
        }
      });
    }, { deep: true }); // 使用 deep 选项可以深度观察数组内部的变化

    return {
      messages,
      msgBody,
      addMessage,
      messageUpdate
    };
  },
};

</script>

<style scoped lang="less">


  .msgBox {
    margin: 5px 0;
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
  }

  .userMsg {
    align-self: flex-end;
    background-color: #DCF8C6;
    padding: 10px;
    border-radius: 10px;
    max-width: 70%;
    margin: 5px 0;
    position: relative;
  }

  .gpt {
    align-self: flex-start;
    background-color: #fff;
    padding: 10px;
    border-radius: 10px;
    max-width: 70%;
    margin: 5px 0;
    border: 1px solid #e0e0e0;
    position: relative;
  }
</style>